// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  const { result } = event
  if (!result) {
    throw new Error('no result')
  }

  const {
    data: [uData],
  } = await db.collection('user').where({ _openid }).get()
  if (!uData) {
    throw new Error('no login user')
  }

  const {
    data: [vData],
  } = await db.collection('vote-result').where({ _openid }).get()
  if (vData) {
    throw new Error('vote only once')
  }

  const user = {
    _id: uData._id,
    nickName: uData.nickName,
    avatarUrl: uData.avatarUrl,
    gender: uData.gender,
    phoneNumber: uData.phoneNumber,
  }

  await db.collection('vote-result').add({ data: { _openid, user, result } })
}
